package cn.deschen.eshop.user.service.impl;

import cn.deschen.eshop.auth.service.DynamicSecurityService;
import cn.deschen.eshop.generator.model.UmsResource;
import cn.deschen.eshop.user.service.UmsResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author hanbin_chen
 * @Description 用户资源
 * @DateTime 2021/1/22 14:11
 * @Version V1.0.0
 */
@Component
public class DynamicSecurityServiceImpl implements DynamicSecurityService {

    @Autowired
    private UmsResourceService resourceService;

    @Override
    public Map<String, ConfigAttribute> loadDataSource() {
        List<UmsResource> resourceList = resourceService.getResourceList();
        return resourceList.stream().collect(
                Collectors.toMap(
                        UmsResource::getUrl,
                        resource -> new SecurityConfig(resource.getId() + ":" + resource.getName()),
                        // 针对可能出现的重复可以处理，不加就会报异常“Duplicate key XXX”，不过业务上不会存在这种情况
                        (key1, key2) -> key2
                )
        );
    }
}
